/**
 * Class: BehaviorManager
 *
 * Purpose: Manages a collection of behaviors
 *
 * Created: Mar 3, 2010 @ 11:28:33 AM
 * @author Ken
 */
package org.openfantasia.ps.modifier.behaviors;

import org.openfantasia.ps.modifier.Behavior;
import org.openfantasia.ps.particle.Particle;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class BehaviorManager {

	protected Map<String, LinkedList<Behavior>> behaviors = new TreeMap<String, LinkedList<Behavior>>();


	public BehaviorManager() {
	}


	public BehaviorManager(BehaviorManager that) {
		copy(that);
	}


	public BehaviorManager copy() {
		return new BehaviorManager(this);
	}


	public void copy(BehaviorManager that) {
		this.behaviors = new TreeMap<String, LinkedList<Behavior>>(that.behaviors);
	}


	public void add(String name, Behavior bhv) {
		LinkedList<Behavior> bhvs = this.behaviors.get(name);
		if (bhvs == null) {
			bhvs = new LinkedList<Behavior>();
			behaviors.put(name, bhvs);
		}
		bhvs.addFirst(bhv);		// Newer behaviors are prepended to older ones
	}


	public void remove(String name, Behavior bhv) {
		List<Behavior> bhvs = this.behaviors.get(name);
		if (bhvs != null) {
			bhvs.remove(bhv);
		}
	}


	public Object getBehaviorValue(String name, Particle particle, double time, Object param) {
		List<Behavior> bhvs = this.behaviors.get(name);
		if (bhvs != null) {
			for (Behavior bhv : bhvs) {
				if (bhv.isActive(particle, time)) {
					param = bhv.getValue(particle, time, param);
				}
			}
		}

		return param;
	}
}
